﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoachingOrganizer.Database.DataAccess;
using CoachingOrganizer.ClientInfrastructure.ServicesEntities.LocalStorage.Tools.MoneyCalculation;
using CoachingOrganizer.Toolkit.Events;

namespace CoachingOrganizer.Database.DataAccessLayer.Tools.MoneyCalculation
{
    public class OccasionalMoneyFlowItemDAL : IOccasionalMoneyFlowItemInfo
    {
        private readonly DbManagerBase _dbManager;
        private OccasionalMoneyFlowItemDA _da;
        private string _name;
        private decimal _amount;
        private DateTime _time;
        private int _sign;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public decimal Amount
        {
            get { return _amount; }
            set { _amount = value; }
        }

        public DateTime Time
        {
            get { return _time; }
            set { _time = value; }
        }

        public int Sign
        {
            get { return _sign; }
            set { _sign = value; }
        }

        public OccasionalMoneyFlowItemDAL(DbManagerBase dbManager)
        {
            _dbManager = dbManager;
        }

        public OccasionalMoneyFlowItemDA CreateNewDA(MoneyCalculationDA moneyCalculation)
        {
            return _da = new OccasionalMoneyFlowItemDA
            {
                MoneyCalculationId = moneyCalculation.Id
            };
        }

        public ActionResult Save()
        {
            _da.Name = _name;
            _da.Amount = _amount;
            _da.Time = _time;
            _da.Sign = _sign;
            return _dbManager.SafeRun(() => _dbManager.Context.InsertOrReplace(_da));
        }

        public bool Load(int id)
        {
            OccasionalMoneyFlowItemDA occasionalMoneyFlowItem = _dbManager.Context.Find<OccasionalMoneyFlowItemDA>(da => da.Id == id);
            if (occasionalMoneyFlowItem == null)
                return false;
            Load(occasionalMoneyFlowItem);
            return true;
        }

        public void Load(OccasionalMoneyFlowItemDA occasionalMoneyFlowItem)
        {
            _da = occasionalMoneyFlowItem;
            _name = _da.Name;
            _amount = _da.Amount;
            _time = _da.Time;
            _sign = _da.Sign;
        }

        public ActionResult Remove()
        {
            if (_da != null)
                return _dbManager.SafeRun(() => _dbManager.Context.Delete<OccasionalMoneyFlowItemDA>(_da.Id));
            return ActionResult.GetErrorResult(new KeyNotFoundException());
        }
    }
}